//
// Created by root on 19-8-5.
//

#include "binder_utils.h"
#include "jni_utils.h"

bool add_service(JNIEnv *env, std::string name, jobject service) {
    jclass service_manager=env->FindClass("android/os/ServiceManager");
    //public static void addService(String name, IBinder service)
    jmethodID add_service_method=env->GetStaticMethodID(service_manager,"addService",
            "(Ljava/lang/String;Landroid/os/IBinder;)V");
    env->CallStaticVoidMethod(service_manager,add_service_method,
            env->NewStringUTF(name.c_str()),service);
    return !TryCatch(env);
}

jobject get_service(JNIEnv *env,std::string name,jclass proxy_class){
    jclass service_manager=env->FindClass("android/os/ServiceManager");
    //public static IBinder getService(String name)
    jmethodID get_service_method=env->GetStaticMethodID(service_manager,"getService",
            "(Ljava/lang/String;)Landroid/os/IBinder;");
    jobject service_remote=env->CallStaticObjectMethod(service_manager,get_service_method,
            env->NewStringUTF(name.c_str()));
    if(!service_remote)
        return nullptr;
    jmethodID proxy_constructor=env->GetMethodID(proxy_class,"<init>",
            "(Landroid/os/IBinder;)V");
    jobject proxy=env->NewGlobalRef(
            env->NewObject(proxy_class,proxy_constructor,
            service_remote)
    );
    return proxy;
}
